package com.cowain.monitor.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.cowain.monitor.dao.PmsDeptPersonDao;
import com.cowain.monitor.dao.PmsEhrContentLogDao;
import com.cowain.monitor.dao.PmsSysDeptDao;
import com.cowain.monitor.dao.PmsSysUserDao;
import com.cowain.monitor.datasources.DataSourceNames;
import com.cowain.monitor.datasources.annotation.DataSource;
import com.cowain.monitor.datasources.config.TransactionConfig;
import com.cowain.monitor.entity.EhrOrganizationEntity;
import com.cowain.monitor.entity.PmsDeptPersonEntity;
import com.cowain.monitor.entity.PmsSysDeptEntity;
import com.cowain.monitor.service.PmsSysDeptService;
import com.cowain.monitor.service.PmsSysUserService;
import com.cowain.monitor.utils.JsonUtils;
import com.cowain.monitor.utils.PmsConstantUtils;
import com.cowain.monitor.utils.PmsProjectUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  
 *  * @author 冬暖
 *  * @projectName pms-monitor
 *  * @title     PmsSysDeptServiceImpl   
 *  * @package    com.cowain.monitor.service.impl  
 *  * @description    组织信息       
 *  * @date   2020/8/11 9:27  
 *  * @version V1.0.0
 *  
 */
@Service
public class PmsSysDeptServiceImpl extends ServiceImpl<PmsSysDeptDao, PmsSysDeptEntity> implements PmsSysDeptService {
    @Autowired
    private PmsProjectUtil projectUtil;
    @Autowired
    private PmsEhrContentLogDao ehrContentLogDao;
    @Autowired
    private PmsSysUserDao userDao;
    @Autowired
    private PmsDeptPersonDao deptPersonDao;
    /**
     * 获取上一次结束时间
     * @return 开始时间
     */
    @Override
    @DataSource(name = DataSourceNames.FIRST)
    public Date findDate(){
        //PmsConstantUtils.EHR_DEPT 标明是查用户表日志还是查 部门日志
        return ehrContentLogDao.findStartTime(PmsConstantUtils.EHR_DEPT,new Date());
    }
    /**
     * 获取部门信息
     * @return 部门信息
     */
    @Override
    @DataSource(name = DataSourceNames.SECOND)
    public List<PmsSysDeptEntity> findDept(Date start){
        List<PmsSysDeptEntity> pmsSysDeptEntities = new ArrayList<>();
        start = null;
        String s = projectUtil.updateTime(projectUtil.getDeptUrl(), start);
        List<EhrOrganizationEntity> deptEntityList = JsonUtils.parseArray(s,"list", EhrOrganizationEntity.class);
        if(deptEntityList.size() > 0){
            int i = 0;
            for (EhrOrganizationEntity organizationEntity : deptEntityList) {
                PmsSysDeptEntity sysDeptEntity = new PmsSysDeptEntity();
                sysDeptEntity.setDeptId(organizationEntity.getOrId().longValue());
                sysDeptEntity.setParentId(organizationEntity.getParentId().longValue());
                sysDeptEntity.setCode(organizationEntity.getCode());
                sysDeptEntity.setName(organizationEntity.getRoName());
                sysDeptEntity.setStatus(0L);
                sysDeptEntity.setRemarks(organizationEntity.getRemark());
                sysDeptEntity.setOrderNum(i);
                sysDeptEntity.setDelFlag(0);
                Integer type = projectUtil.findCompany(StringUtils.isBlank(organizationEntity.getCategory()) ? "部门": organizationEntity.getCategory());
                sysDeptEntity.setIsCompany(type);
                sysDeptEntity.setIsDel(0);
                sysDeptEntity.setHrId(organizationEntity.getLeader() == null ? null:organizationEntity.getLeader());
                sysDeptEntity.setCreateBy(organizationEntity.getCreatorId());
                sysDeptEntity.setCreateDate(organizationEntity.getCreateTime());
                sysDeptEntity.setUpdateBy(organizationEntity.getUpdatorId());
                sysDeptEntity.setUpdateDate(organizationEntity.getUpdateTime());
                sysDeptEntity.setLeader(organizationEntity.getLeader());
                if (null == organizationEntity.getLevel()){
                    organizationEntity.setLevel(1000136);
                }
                sysDeptEntity.setLevel(organizationEntity.getLevel().toString());
                sysDeptEntity.setLevelName(organizationEntity.getLevelName());
                pmsSysDeptEntities.add(sysDeptEntity);
                i++;
            }
            List<PmsSysDeptEntity> insert = new ArrayList<>();
            List<PmsSysDeptEntity> update = new ArrayList<>();
            pmsSysDeptEntities.forEach(dept -> {
                PmsSysDeptEntity deptEntity = baseMapper.findDeptById(dept.getDeptId());
                if(deptEntity != null){
                    update.add(dept);
                }else {
                    insert.add(dept);
                }
            });
            if (insert.size() > 0){
                List<List<PmsSysDeptEntity>> split = projectUtil.split(insert, 12);
                split.forEach(dept ->
                        baseMapper.insertDepts(dept)
                );
            }
            if(update.size() > 0){
                baseMapper.deletDept(update);
                List<List<PmsSysDeptEntity>> splits = projectUtil.split(update, 12);
                splits.forEach(dept ->
                        baseMapper.insertDepts(dept)
                );
            }

        }else {
            System.out.println("暂未有数据同步");
        }
        return baseMapper.findDeptList(PmsConstantUtils.IS_DEL);
    }
    /**
     * 保存组织信息
     */
    @Override
    @DataSource(name = DataSourceNames.FIRST)
    @Transactional(value = TransactionConfig.DEFAULT_TX,rollbackFor = Exception.class)
    public void insertDept(List<PmsSysDeptEntity> list){
        List<PmsSysDeptEntity> insertDept = new ArrayList<>();
        List<PmsSysDeptEntity> updateDept = new ArrayList<>();
        List<PmsSysDeptEntity> removeDept = new ArrayList<>();
        List<PmsDeptPersonEntity> insertPerson = new ArrayList<>();
        List<PmsDeptPersonEntity> updatePerson = new ArrayList<>();
        List<PmsDeptPersonEntity> removePerson = new ArrayList<>();
        list.forEach(dept -> {
            PmsSysDeptEntity sysDeptEntity =  baseMapper.findDept(dept.getDeptId());
            if(StringUtils.isNotBlank(dept.getHrId())){
                Long userId = baseMapper.findByHrId(dept.getHrId());
                PmsDeptPersonEntity person = deptPersonDao.findByDeptAndUser(dept.getDeptId(),userId);
                PmsDeptPersonEntity personEntity = new PmsDeptPersonEntity();
                personEntity.setDeptId(dept.getDeptId());
                //todo 暂时写死
                if (null == userId){
                    userId = 1L;
                }
                personEntity.setUserId(userId);
                if(StringUtils.isNotBlank(dept.getCreateBy())){
                    Long createId = baseMapper.findByHrId(dept.getCreateBy());
                    personEntity.setCreateBy(createId);
                }else {
                    personEntity.setCreateBy(null);
                }
                personEntity.setCreateDate(dept.getCreateDate());
                personEntity.setUpdateBy(null);
                personEntity.setUpdateDate(null);
                personEntity.setStatus(0);
                if(person != null){
                    updatePerson.add(personEntity);
                    removePerson.add(person);
                }else {
                    PmsDeptPersonEntity personEntity1=  deptPersonDao.findByUserId(dept.getDeptId());
                    if(personEntity1 != null){
                        updatePerson.add(personEntity);
                        removePerson.add(personEntity1);
                    }else {
                        insertPerson.add(personEntity);
                    }
                }
            }

            if(sysDeptEntity != null){
               updateDept.add(dept);
               removeDept.add(sysDeptEntity);
            }else {
                insertDept.add(dept);
            }

        });
        List<PmsSysDeptEntity> list1 = new ArrayList<>();
        boolean flag = false;
        List<Long> lists = projectUtil.addDeptList(insertDept, list1);
        if(insertDept.size() > 0 && lists.size() > 0){
            List<PmsSysDeptEntity> list2 = new ArrayList<>();
            insertDept.forEach(info -> {
                if(info.getDeptId() == null){
                    list2.add(info);
                }
            });
            insertDept.removeAll(list2);
            if(insertDept.size() > 0){
                List<List<PmsSysDeptEntity>> split = projectUtil.split(insertDept, 12);
                for (List<PmsSysDeptEntity> clientEntities : split) {
                    baseMapper.insertDept(clientEntities);
                }
                flag = true;
            }
        }
        if(updateDept.size() > 0){
            if(list1.size() > 0){
                updateDept.addAll(list1);
            }
            if(removeDept.size() > 0){
                baseMapper.deleteDeptes(updateDept);
            }
            List<List<PmsSysDeptEntity>> split = projectUtil.split(updateDept, 12);
            for (List<PmsSysDeptEntity> pmsClientEntities : split) {
                baseMapper.updateDept(pmsClientEntities);
            }
        }
        if(list1.size() ==0){
            list1.addAll(updateDept);
        }
        if(lists.size() > 0 || list1.size() > 0) {
            List<PmsSysDeptEntity> pmsClientEntities = new ArrayList<>();
            if(flag){
                pmsClientEntities.addAll(insertDept);
            }
            projectUtil.addEhrLog(pmsClientEntities, updateDept, PmsConstantUtils.EHR_DEPT, PmsConstantUtils.EHR_DEPT,new Date());
        }
        addDeptPerson(insertPerson,updatePerson,removePerson);
    }

    /**
     * 保存负责人
     * @param removeDept 删除集合
     * @param insertDept 添加集合
     * @param updateDept 修改部门
     */
    private void addDeptPerson(List<PmsDeptPersonEntity> insertDept, List<PmsDeptPersonEntity> updateDept,List<PmsDeptPersonEntity> removeDept) {
        List<PmsDeptPersonEntity> list1 = new ArrayList<>();
        boolean flag = false;
        List<Long> lists = projectUtil.addPersonList(insertDept, list1);
        if(insertDept.size() > 0 && lists.size() > 0){
            List<PmsDeptPersonEntity> list2 = new ArrayList<>();
            insertDept.forEach(info -> {
                if(info.getDeptId() == null){
                    list2.add(info);
                }
            });
            insertDept.removeAll(list2);
            if(insertDept.size() > 0){
                List<List<PmsDeptPersonEntity>> split = projectUtil.split(insertDept, 12);
                for (List<PmsDeptPersonEntity> clientEntities : split) {
                    deptPersonDao.insertPerson(clientEntities);
                }
                flag = true;
            }
        }
        if(updateDept.size() > 0){
            if(list1.size() > 0){
                updateDept.addAll(list1);
            }
            if(removeDept.size() > 0){
                deptPersonDao.deleteDeptes(updateDept);
            }
            List<List<PmsDeptPersonEntity>> split = projectUtil.split(updateDept, 12);
            for (List<PmsDeptPersonEntity> pmsClientEntities : split) {
                deptPersonDao.insertPerson(pmsClientEntities);
            }
        }
        if(list1.size() ==0){
            list1.addAll(updateDept);
        }
        if(lists.size() > 0 || list1.size() > 0) {
            List<PmsDeptPersonEntity> pmsClientEntities = new ArrayList<>();
            if(flag){
                pmsClientEntities.addAll(insertDept);
            }
            projectUtil.addEhrLog(pmsClientEntities, updateDept, PmsConstantUtils.EHR_DEPT, PmsConstantUtils.EHR_DEPT,new Date());
        }
    }

    /**
     * 修改部门信息
     */
    @Override
    @DataSource(name = DataSourceNames.SECOND)
    public void updateDeptList(List<PmsSysDeptEntity> list){
        list.forEach(so -> {
            if(so.getDeptId() == null){
                so.setIsDel(0);
            }else {
                so.setIsDel(1);
            }
        });
        List<PmsSysDeptEntity> collect = list.stream()
                .filter(s -> s.getIsDel() == 1)
                .collect(Collectors.toList());
        List<List<PmsSysDeptEntity>> split = projectUtil.split(collect, 12);
        for (List<PmsSysDeptEntity> customerEntities : split) {
            baseMapper.updateDepts(customerEntities);
        }
    }
}
